<template>
  <div class="content">
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.title" placeholder="标题" prefix-icon="el-icon-search" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getTableData()">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="add()" type="primary" >新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是确定批量删除吗？" @onConfirm="delHandle(null)">
          <template #reference>
            <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!--这里是表格-->
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 99%"
      sroll
      border
      stripe
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.type === 1">家庭作业</el-tag>
          <el-tag type="" v-else-if="scope.row.type === 2">校内通知</el-tag>
          <el-tag type="warning" v-else-if="scope.row.type === 3">学校公告</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="addressee" label="收件人"></el-table-column>
      <el-table-column prop="nickname" label="发布人名称" ></el-table-column>
      <el-table-column prop="createTime" label="发布时间" ></el-table-column>
      <!--这里是操作栏-->
      <el-table-column label="操作" width="200" >
        <template #default="scope">

          <el-button @click="detailHandle(scope.row)" type="text">详情</el-button>
          <el-divider direction="vertical" ></el-divider>

          <el-button @click="editHandle(scope.row)" type="text"  >编辑</el-button>
          <el-divider direction="vertical" ></el-divider>

          <el-popconfirm title="确定要删除这条记录吗？" @onConfirm="delHandle(scope.row.id)" >
            <template #reference>
              <el-button type="text">删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <!--新增、编辑对话框-->
    <el-dialog title="通知信息"
               :visible.sync="dialogVisible"
               width="50%"
               @open="loadingForm('editForm')"
               @close="resetForm('editForm')">
      <el-form :model="editForm" ref="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="发送对象" v-show="!editForm.id" class="">
          <el-radio-group  v-model="sendObj">
            <el-radio :label="1">全部班级</el-radio>
            <el-radio :label="2">部分班级</el-radio>
            <el-radio :label="3">按人发放</el-radio>
            <el-tooltip content="关联学生的家长" placement="top">
              <el-switch
                v-model="relation"
                inactive-text="👨‍👨‍👧‍👦"
                active-color="#13ce66"
                active-value="1"
                inactive-value="0"
              >
              </el-switch>
            </el-tooltip>
          </el-radio-group>

        </el-form-item>
        <el-form-item v-show="!editForm.id && sendObj === 2 || sendObj === 3">
          <el-checkbox-group v-model="checkList" v-show="sendObj === 2">
            <el-checkbox v-for="option in options" :key="option.id" :label="option.classId">
              {{option.myClass.grade.year+""+option.myClass.grade.name+""+option.myClass.name}}
            </el-checkbox>
          </el-checkbox-group>
          <el-card class="box-card" v-show="sendObj === 3">
            <template #header>
              <div>
                <span>班级名称： </span>
                <el-select v-model="selectValue" filterable placeholder="选择班级" size="medium" @change="changeSelectHandle">
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.myClass.grade.year+item.myClass.grade.name+item.myClass.name"
                    :value="item.classId"
                  >
                  </el-option>
                </el-select>
              </div>
            </template>
            <el-table
              ref="multipleTable2"
              :data="tableData2"
              style="width: 100%;"
              stripe
              header-cell-class-name="padding2Zero"
              cell-class-name="padding2Zero"
              @selection-change="handleSelectionChange2"

            >
              <el-table-column type="selection" header-align="center" align="center"/>
              <el-table-column property="schoolno" label="学号" header-align="center" align="center"/>
              <el-table-column property="name" label="姓名" header-align="center" align="center"/>
            </el-table>
          </el-card>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="editForm.type" size="small">
            <el-radio :label="1" border>家庭作业</el-radio>
            <el-radio :label="2" border>校内通知</el-radio>
            <el-radio :label="3" border>学校公告</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
            type="text"
            placeholder="请输入标题"
            v-model="editForm.title"
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <div id="demo1"></div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="dialogDetailVisible" title="详情" width="50%">
      <el-card>
        <div v-html="detail.content" style="min-height: 100px"></div>
      </el-card>
    </el-dialog>

    <!--分页组件-->
    <div style="float: right;margin-top: 22px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
import {
  changeSelectHandle,
  del,
  getListClasses,
  getTableData,
  submitEditForm
} from '@/api/Questionnaire/questionnaire'

export default {
  name: 'Questionnaire',
  data() {
    return {
      searchForm: {},

      // 根据多选的数量，将其批量按钮可用/不可用进行变化
      multipleSelection: [],
      delBtlStatu: true,

      tableData: [],

      // 分页用到的属性
      total: 0,
      current: 1,
      size: 10,

      // 编辑用到的对话框和对应的v-model绑定的数据和表单验证规则
      dialogVisible: false,
      editForm: {type:1},
      editFormRules: {
        title: {required: true, message: '请输入标题', trigger: 'blur'}
      },

      // 详情对话框，
      dialogDetailVisible: false,
      // 查看富文本内容
      detail: {},

      // 富文本编辑器
      editor: null,

      sendObj: 1,
      relation: 0,
      // 勾选班级的id值
      checkList: [],
      // 班级多选框和select选择器渲染的值
      options: [],

      // select选择器选择的值
      selectValue: '',
      // 选择后查询所对应班级学生
      tableData2: [],
      // 勾选班级学生的id值
      multipleSelection2: [],

    }
  },


  methods: {
    // 指定人员的select选择器值变化
    changeSelectHandle(val){
      changeSelectHandle(val).then(res => {
        console.log(res)
        this.tableData2 = res.data.data
      })
    },

    // 选择指定人员的复选框改变的事件方法
    handleSelectionChange2(val) {
      this.multipleSelection2 = val
    },

    getTableData(){
      getTableData(this.searchForm.title,this.current,this.size).then(res => {
        console.log(res)
        this.tableData = res.data.data.records
        this.current = res.data.data.current
        this.size = res.data.data.size
        this.total = res.data.data.total
      })
    },

    detailHandle(row) {
      this.dialogDetailVisible = true
      this.detail.content = row.content
    },
    buildEditor(){
      this.$nextTick(() => {
        const editor = new E('#demo1')
        editor.config.uploadFileName = 'file'
        editor.config.uploadImgServer = 'http://localhost:8085/files/editorUploadFile'
        editor.config.uploadImgMaxLength = 1
        editor.config.onchange = (newHtml) => {
          this.editForm.content = newHtml
        }
        editor.create()
        this.editor = editor
      })
    },
    add(){
      this.dialogVisible = true
      this.buildEditor()
    },
    //点击编辑的事件，用于数据回显
    editHandle(row) {
      this.dialogVisible = true
      this.buildEditor()
      this.$nextTick(() => {
        this.editForm = JSON.parse(JSON.stringify(row))
        this.editor.txt.html(row.content)
      })
    },
    // 新增、编辑表单提交
    submitEditForm(formName) {
      if (!this.editForm.id){
        this.editForm.notice = JSON.parse(JSON.stringify(this.editForm))
        let noticeClasses = []
        if(this.sendObj === 1){
          this.options.forEach(o => {
            noticeClasses.push({classId : o.classId, isAll : 1})
          })
        }else if(this.sendObj === 2){
          this.checkList.forEach(o => {
            noticeClasses.push({classId : o, isAll : 1})
          })
        }else if(this.sendObj === 3){
          noticeClasses.push({
            classId : this.selectValue,
            sysUserIds: this.multipleSelection2.length === this.tableData2.length ? '' :
              this.multipleSelection2.map(m => {return m.id}).join(","),
            isAll : this.multipleSelection2.length === this.tableData2.length ? 1 : 0
          })
        }
        this.editForm.noticeClasses = noticeClasses
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          submitEditForm(this.editForm).then(res => {
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
                onClose:() => {
                  this.getTableData()
                }
              });
              this.dialogVisible = false
            })
        } else {
          console.log('error rule');
          return false;
        }
      })
    },

    // 触发事件为有复选框发生变化，会传递所有勾选的行数据对象数组
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //设置批量删除的按钮的可用/不可用
      this.delBtlStatu = val.length === 0
    },
    //这里是删除功能
    delHandle(id) {
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      del(ids).then(res=>{
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose:() => {
            this.getTableData()
          }
        });
      })
    },
    loadingForm(formName) {
      getListClasses().then(res => {
        this.options = res.data.data
        console.log(this.options)
      })
    },
    // 新增、编辑对话框公用一个，新增不会回显，所以需要对其清空表单中的内容，以免切换(新增/编辑)后数据还在
    resetForm(formName) {
      this.dialogVisible = false
      this.sendObj = 1
      this.relation = 0
      this.checkList = []
      this.selectValue = ""
      this.tableData2 = []
      this.$refs[formName].resetFields();
      this.editForm = {type:1}
      this.editor.destroy()
    },

    //这里是分页
    handleSizeChange(val) {
      this.size = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getTableData()
    },

  },

  created() {
    this.getTableData()
  },
}
</script>
<style scope>
.padding2Zero{
  padding: 0 !important;
}
.el-switch{
  position: absolute !important;
  right: 0 !important;
  top: 10px !important;
}
</style>
